筆者註: 其實不只是遊戲開發的存檔功能,就連嵌入式系統中也很常使用到此 Pattern 來定期保存系統 Snapshot,以防止外部環境異常斷電 (SPOR),以便後續的系統環境 Recovery
Originator (發起人): 負責創建一個 Memento,用於存儲其當前內部狀態
Memento (備忘錄): 存儲 Originator 的內部狀態,但不應對 Originator 的狀態進行任何操作
Caretaker (管理者): 負責保存和恢復 Originator 的 Memento 對象
// Memento class to store system state
class SystemStateMemento {
private:
std::string state;
public:
SystemStateMemento(const std::string& s) : state(s) {}
std::string getState() const { return state; }
};
// Originator class
class EmbeddedSystem {
private:
std::string state;
public:
void setState(const std::string& s) { state = s; }
std::string getState() const { return state; }
SystemStateMemento saveStateToMemento() { return SystemStateMemento(state); }
void getStateFromMemento(const SystemStateMemento& memento) { state = memento.getState(); }
};
// Caretaker class
class Caretaker {
private:
std::vector<SystemStateMemento> mementoList;
public:
void add(const SystemStateMemento& state) { mementoList.push_back(state); }
SystemStateMemento get(int index) { return mementoList[index]; }
};
int main() {
EmbeddedSystem system;
Caretaker caretaker;
// Set initial state and save to memento
system.setState("Initial State");
caretaker.add(system.saveStateToMemento());
// Change system state and save to memento
system.setState("Running");
caretaker.add(system.saveStateToMemento());
// Simulate SPOR (Sudden Power Off Recovery)
system.setState("Unknown");
// Restore state from memento after SPOR
system.getStateFromMemento(caretaker.get(1));
std::cout << "System State after SPOR: " << system.getState() << std::endl;
}
Output:
System State after SPOR: Running